package com.dzsw.netty.wspb.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class PingPongHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    public static PingPongHandler INSTANCE = new PingPongHandler();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        frame.retain();
        if (frame instanceof PingWebSocketFrame) {
            log.info("客户端ping成功");
            ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // ping消息
        if (frame instanceof PongWebSocketFrame) {
            log.info("客户端pong成功");
            return;
        }
        ctx.fireChannelRead(frame);
    }

}
